package com.dongdong.shiro;

import com.dongdong.api.AdminAPI;
import com.dongdong.api.SellerAPI;
import com.dongdong.api.UserAPI;
import com.dongdong.em.Result;
import com.dongdong.model.TbAdmin;
import com.dongdong.model.TbSeller;
import com.dongdong.model.TbUser;
import com.dongdong.user.UserEnum;
import com.dongdong.user.UserToken;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

public class LoginRealm extends AuthorizingRealm {

    @Autowired
    private AdminAPI adminAPI;

    @Autowired
    private SellerAPI sellerAPI;

    //授权管理
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    //认证管理
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        SimpleAuthenticationInfo simple = null;
        //创建一个类将原本的usernamepasswordtoken继承然后添加另外的参数  分辨admin还是seller
        UserToken usernamePasswordToken = (UserToken) authenticationToken;
        //判断是admin还是seller
        if (UserEnum.ADMIN.equals(usernamePasswordToken.getUserEnum())) {
            Result<TbAdmin> result = adminAPI.getAdminByName(usernamePasswordToken.getUsername());
            //如果data中没有数据就说明没有查询到
            TbAdmin adminByName = result.getData();
            if (adminByName == null) {
                return null;
            }
            simple = new SimpleAuthenticationInfo(adminByName, adminByName.getPassword(), ByteSource.Util.bytes(adminByName.getSalt()), "admin");
            return simple;
        } else if (UserEnum.SELLER.equals(usernamePasswordToken.getUserEnum())) {
            TbSeller sellerByName = sellerAPI.getSellerByName(usernamePasswordToken.getUsername());
            if (sellerByName == null) {
                return null;
            }
            simple = new SimpleAuthenticationInfo(sellerByName,sellerByName.getPassword(), ByteSource.Util.bytes(sellerByName.getSalt()), "seller");
            return simple;
        }
        return simple;
    }
}
